package com.yunhe.common.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * Json工具类
 * @author liuronglei
 */
public class JsonUtil {

    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        // 忽略未知的字段
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 读取不认识的枚举时，当null值处理
        mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
        mapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
    }

    /**
     * 获得ObjectMapper
     */
    public static ObjectMapper getObjectMapper() {
        return mapper;
    }

    public static String toJson(Object o) throws JsonProcessingException {
        return mapper.writeValueAsString(o);
    }

    public static <T> T readValue(String json, TypeReference<T> valueTypeRef) throws IOException {
        return mapper.readValue(json, valueTypeRef);
    }

    public static <T> T readValue(String json, Class<T> valueType) throws IOException {
        return mapper.readValue(json, valueType);
    }
}
